/**
 * Copyright 2010-present Facebook.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.facebook.widget;

import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ListView;
import com.facebook.FacebookException;
import com.facebook.android.R;
import com.facebook.internal.Utility;
import com.facebook.model.GraphUser;
import com.facebook.widget.FriendPickerFragment;


public class MyFragmentFriendPicker extends FriendPickerFragment 
{
	private static final int PROFILE_PICTURE_PREFETCH_BUFFER = 5;
	private String searchText;
	private boolean hasSearchTextChangedSinceLastQuery;
	private Timer searchTextTimer;
	private static final int searchTextTimerDelayInMilliseconds = 2 * 1000;
	private ListView listView;
	
	// PlacePickerFragment
    public MyFragmentFriendPicker(Bundle args) 
    {
		// TODO Auto-generated constructor stub
    	super(args);
	}

	
    @Override
    void setupViews(ViewGroup view) 
    {
       
            listView = (ListView) view.findViewById(R.id.com_facebook_picker_list_view);

            View searchHeaderView = getActivity().getLayoutInflater().inflate(R.layout.com_facebook_picker_search_box, listView, false);

            listView.addHeaderView(searchHeaderView, null, false);

            EditText searchBox = (EditText) view.findViewById(R.id.com_facebook_picker_search_text);

            searchBox.addTextChangedListener(new SearchTextWatcher());
            
            listView.setOnScrollListener(onScrollListener);
            
        
    }
    
    private ListView.OnScrollListener onScrollListener = new ListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            reprioritizeDownloads();
        }
    };
    
    private void reprioritizeDownloads() 
    {
    	if(listView == null)
    		return;
    	
        int lastVisibleItem = listView.getLastVisiblePosition();
        if (lastVisibleItem >= 0) 
        {
            int firstVisibleItem = listView.getFirstVisiblePosition();
            
            // we need to account for search textbox
            adapter.prioritizeViewRange(firstVisibleItem-1, lastVisibleItem-1, PROFILE_PICTURE_PREFETCH_BUFFER);
        }
    }


    
    public void onSearchBoxTextChanged(String searchText, boolean forceReloadEventIfSameText) 
    {
        if (!forceReloadEventIfSameText && Utility.stringsEqualOrEmpty(this.searchText, searchText)) 
        {
            return;
        }

        if (TextUtils.isEmpty(searchText)) 
        {
            searchText = null;
        }
        this.searchText = searchText;

        // If search text is being set in response to user input, it is wasteful to send a new request
        // with every keystroke. Send a request the first time the search text is set, then set up a 2-second timer
        // and send whatever changes the user has made since then. (If nothing has changed
        // in 2 seconds, we reset so the next change will cause an immediate re-query.)
        hasSearchTextChangedSinceLastQuery = true;
        if (searchTextTimer == null) 
        {
            searchTextTimer = createSearchTextTimer();
        }
    }
    

    private void FilterWithName(final String SearchStri)
    {
    	
    	//PBUtility.LOG("Filtering-----------------");
    	
    	this.setFilter(new GraphObjectFilter<GraphUser>() 
		{
		        @Override
		        public boolean includeItem(GraphUser graphObject) 
		        {
		        	if(SearchStri == null || SearchStri.isEmpty())
		        		return true;
		        	
		            if( graphObject.getName().toLowerCase().contains(SearchStri.toLowerCase()))
		            {
		            	//PBUtility.LOG("Filtering----------------- true " + graphObject.getName());
		                return true;
		            }
		            else
		            {
		            	//PBUtility.LOG("Filtering----------------- false " + graphObject.getName());
		                return false;
		            }
		        }
		  });
    	
    	this.adapter.rebuildAndNotify();
    }
	

    
    private Timer createSearchTextTimer() 
    {
        Timer timer = new Timer();
        timer.schedule( new TimerTask()
				        {
				            @Override
				            public void run() 
				            {
				                onSearchTextTimerTriggered();
				            }
				        }, 0, searchTextTimerDelayInMilliseconds
				        );

        return timer;
    }
    
    @Override
    void onLoadingData() 
    {
        hasSearchTextChangedSinceLastQuery = false;
    }
    
    private void onSearchTextTimerTriggered() 
    {
    	final String Str = this.searchText;
        if (hasSearchTextChangedSinceLastQuery) 
        {
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(new Runnable() 
            {
                @Override
                public void run() 
                {
                    FacebookException error = null;
                    try 
                    {
                    	FilterWithName(Str);
                    	//
                    	loadData(false);
                    	
                       
                    } 
                    catch (FacebookException fe) 
                    {
                        error = fe;
                    } 
                    catch (Exception e) 
                    {
                        error = new FacebookException(e);
                    } 
                    finally 
                    {
                        if (error != null)
                        {
                            OnErrorListener onErrorListener = getOnErrorListener();
                            if (onErrorListener != null) 
                            {
                               // onErrorListener.onError(PlacePickerFragment.this, error);
                            } 
                            else 
                            {
                                //Logger.log(LoggingBehavior.REQUESTS, TAG, "Error loading data : %s", error);
                            }
                        }
                    }
                }
            });
        } 
        else
        {
            // Nothing has changed in 2 seconds. Invalidate and forget about this timer.
            // Next time the user types, we will fire a query immediately again.
            searchTextTimer.cancel();
            searchTextTimer = null;
        }
    }
    
   
      
    
    private class SearchTextWatcher implements TextWatcher 
    {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after)
        {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) 
        {
            onSearchBoxTextChanged(s.toString(), false);
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    }
    
}
